use actix_web::{web, HttpResponse, Responder};
use serde_json::json;
use crate::model::environment::CreateEnvironmentData;
use crate::service::environment::EnvironmentService;

pub async fn get_environment_data(
    service: web::Data<EnvironmentService>
) -> impl Responder {
    match service.get_all_data().await {
        Ok(data) => HttpResponse::Ok().json(data),
        Err(e) => {
            println!("错误: {:?}", e);
            HttpResponse::InternalServerError().body(e.to_string())
        }
    }
}

pub async fn add_environment_data(
    service: web::Data<EnvironmentService>,
    data: web::Json<CreateEnvironmentData>,
) -> impl Responder {
    match service.create_data(data.into_inner()).await {
        Ok(id) => HttpResponse::Created().json(json!({ "id": id })),
        Err(e) => {
            println!("错误: {:?}", e);
            HttpResponse::InternalServerError().body(e.to_string())
        }
    }
}